package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("ProducerRestController")
public class ProducerRestController extends CmiEmaController {

	/**
	 * Create a new Producer entity
	 * 
	 */
	@RequestMapping(value = "/newProducer", method = RequestMethod.POST)
	@ResponseBody
	public Object newProducer(@RequestBody Producer producer) {
		producerService.saveProducer(producer);
		return JSONObject.parse(cmiPsonService.toJsonString(producerDAO.findProducerByPrimaryKey(producer.getId()), 2));
	}

	@RequestMapping(value = "/restNewProducer", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewProducer(@RequestBody String producerJson) {
		Producer producer = new Gson().fromJson(producerJson, Producer.class);
		appendReferences(producer);
		producerService.saveProducer(producer);
		return JSONObject.parse(cmiPsonService.toJsonString(producerDAO.findProducerByPrimaryKey(producer.getId()), 2));
	}

	@RequestMapping(value = "/saveProducer", method = RequestMethod.PUT)
	@ResponseBody
	public Producer saveProducer(@RequestBody Producer producer) {
		producerService.saveProducer(producer);
		return producerDAO.findProducerByPrimaryKey(producer.getId());
	}

	@RequestMapping(value = "/restSaveProducer", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveProducer(@RequestBody String producerJson) {
		Producer producer = new Gson().fromJson(producerJson, Producer.class);
		appendReferences(producer);
		CmiPsonService cmiPsonService = new CmiPsonService();
		producerService.saveProducer(producer);
		return JSONObject.parse(cmiPsonService.toJsonString(producerDAO.findProducerByPrimaryKey(producer.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteProducer/{producerId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteProducer(@PathVariable Integer producerId) {
		Producer producer = producerDAO.findProducerByPrimaryKey(producerId);
		producerService.deleteProducer(producer);
	}

	@RequestMapping(value = "/restConfirmDeleteProducers")
	@ResponseBody
	public Object restConfirmDeleteProducers(@RequestBody Set<Integer> deleteProducersIds) {
		Set<Producer> deleteProducers = producerDAO.findProducersByIds(deleteProducersIds);
		Set<Producer> referencedProducers = producerService.loadReferenceProducers(deleteProducers);
		deleteProducers.removeAll(referencedProducers);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedProducers);
		jsonObject.put("deleteEntitys", deleteProducers);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteProducers")
	@ResponseBody
	public Object restDeleteProducers(@RequestBody Set<Producer> deleteProducers) {
		Iterator<Producer> iterator = deleteProducers.iterator();
		while (iterator.hasNext()) {
			Producer currentProducer = iterator.next();
			producerService.deleteProducer(currentProducer);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listProducers");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadProducer/{producerId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadProducer(@PathVariable Integer producerId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(producerDAO.findProducerByPrimaryKey(producerId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadProducerAddress/{producerId}/address", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadProducerAddress(@PathVariable Integer producerId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(producerDAO.findProducerByPrimaryKey(producerId).getAddress(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadProducerFoods/{producerId}/foods/{relatedfoodId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadProducerFoods(@PathVariable Integer producerId, @PathVariable Integer relatedfoodId,
			@RequestBody CmiPagination cmiPagination) {
		Food food = foodDAO.findFoodByPrimaryKey(relatedfoodId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(food, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadProducerPurchaseadditives/{producerId}/purchaseadditives/{relatedpurchaseadditiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadProducerPurchaseadditives(@PathVariable Integer producerId,
			@PathVariable Integer relatedpurchaseadditiveId, @RequestBody CmiPagination cmiPagination) {
		Purchaseadditive purchaseadditive = purchaseadditiveDAO
				.findPurchaseadditiveByPrimaryKey(relatedpurchaseadditiveId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(purchaseadditive, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadProducerPurchasematerials/{producerId}/purchasematerials/{relatedpurchasematerialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadProducerPurchasematerials(@PathVariable Integer producerId,
			@PathVariable Integer relatedpurchasematerialId, @RequestBody CmiPagination cmiPagination) {
		Purchasematerial purchasematerial = purchasematerialDAO
				.findPurchasematerialByPrimaryKey(relatedpurchasematerialId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(purchasematerial, 2, cmiPagination));
	}

	public void appendReferences(Producer producer) {

		Address address = producer.getAddress();
		if (address != null)
			producer.setAddress(addressService.findAddressByPrimaryKey(address.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Food> foodsForProducer = new HashSet<>();
		for (Food food_Producer : producer.getFoodsForProducer()) {
			foodsForProducer.add(foodService.findFoodByPrimaryKey(food_Producer.getId()));
		}
		producer.setFoodsForProducer(foodsForProducer);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Purchaseadditive> purchaseadditivesForProducer = new HashSet<>();
		for (Purchaseadditive purchaseadditive_Producer : producer.getPurchaseadditivesForProducer()) {
			purchaseadditivesForProducer
					.add(purchaseadditiveService.findPurchaseadditiveByPrimaryKey(purchaseadditive_Producer.getId()));
		}
		producer.setPurchaseadditivesForProducer(purchaseadditivesForProducer);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Purchasematerial> purchasematerialsForProducer = new HashSet<>();
		for (Purchasematerial purchasematerial_Producer : producer.getPurchasematerialsForProducer()) {
			purchasematerialsForProducer
					.add(purchasematerialService.findPurchasematerialByPrimaryKey(purchasematerial_Producer.getId()));
		}
		producer.setPurchasematerialsForProducer(purchasematerialsForProducer);
	}

	@RequestMapping(value = "/restGetProducerAddress/{producerId}/address", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetProducerAddress(@PathVariable Integer producerId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(producerDAO.findProducerByPrimaryKey(producerId).getAddress(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetProducerFoods/{producerId}/foods", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetProducerFoods(@PathVariable Integer producerId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(producerDAO.findProducerByPrimaryKey(producerId).getFoodsForProducer(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetProducerPurchaseadditives/{producerId}/purchaseadditives", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetProducerPurchaseadditives(@PathVariable Integer producerId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				producerDAO.findProducerByPrimaryKey(producerId).getPurchaseadditivesForProducer(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetProducerPurchasematerials/{producerId}/purchasematerials", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetProducerPurchasematerials(@PathVariable Integer producerId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				producerDAO.findProducerByPrimaryKey(producerId).getPurchasematerialsForProducer(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListProducers", method = RequestMethod.GET)
	@ResponseBody
	public Object restListProducers() {
		return JSONObject.parse(cmiPsonService.toJsonString(producerService.loadProducers(), 2));
	}

	@RequestMapping(value = "/restListProducersPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListProducersPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = producerPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Producer> producers = producerDAO.findAllProducers(startResult, cmiPagination.getPaginationSize());
		String producerString = cmiPsonService.toPsonString(producers, 2, cmiPagination);

		return JSONObject.parse(producerString);
	}

	@RequestMapping("/producerSelectBox")
	@ResponseBody
	public JSONObject producerSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Address":
				entitySet = addressService.loadAddresssByIdSet(searchValue);
				break;

			// 被引用键
			case "Food":
				entitySet = foodService.loadFoodsByIdSet(searchValue);
				break;
			case "Purchaseadditive":
				entitySet = purchaseadditiveService.loadPurchaseadditivesByIdSet(searchValue);
				break;
			case "Purchasematerial":
				entitySet = purchasematerialService.loadPurchasematerialsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Address":
				entitySet = addressDAO.findAllAddresss((pageNumber - 1) * paginationSize, paginationSize);
				count = addressService.countAddresss();
				break;

			// 被引用键
			case "Food":
				entitySet = foodDAO.findAllFoods((pageNumber - 1) * paginationSize, paginationSize);
				count = foodService.countFoods();
				break;
			case "Purchaseadditive":
				entitySet = purchaseadditiveDAO.findAllPurchaseadditives((pageNumber - 1) * paginationSize,
						paginationSize);
				count = purchaseadditiveService.countPurchaseadditives();
				break;
			case "Purchasematerial":
				entitySet = purchasematerialDAO.findAllPurchasematerials((pageNumber - 1) * paginationSize,
						paginationSize);
				count = purchasematerialService.countPurchasematerials();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Address":
				entitySet = addressDAO.findAddressByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = addressService.countAddresssByName(queryword);
				break;

			// 被引用键
			case "Food":
				entitySet = foodDAO.findFoodByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodService.countFoodsByName(queryword);
				break;
			case "Purchaseadditive":
				entitySet = purchaseadditiveDAO.findPurchaseadditiveByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = purchaseadditiveService.countPurchaseadditivesByName(queryword);
				break;
			case "Purchasematerial":
				entitySet = purchasematerialDAO.findPurchasematerialByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = purchasematerialService.countPurchasematerialsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
